//
//  LGTableViewController.m
//  LGBlueToothDemo1
//
//  Created by shuangwuxu on 2019/1/16.
//  Copyright © 2019年 ZnLG. All rights reserved.
//

#import "LGTableViewController.h"
#import "LGViewController.h"
#import "LGConnectSuccessVC.h"
#import <CoreBluetooth/CoreBluetooth.h>

@interface LGTableViewController ()<CBCentralManagerDelegate,CBPeripheralDelegate>
@property(nonatomic,strong)NSMutableArray *dataSource;
@property (strong,nonatomic) CBCentralManager *centralManager;//中心设备管理器
@property (strong,nonatomic) CBPeripheral * succeedPeripheral;//连接成功的外围设备
@end

@implementation LGTableViewController

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
}

- (void)dealloc{
    self.centralManager.delegate = nil;
    self.centralManager = nil;
    [self.dataSource removeAllObjects];
    self.succeedPeripheral = nil;
    NSLog(@"中心服务器销毁了");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"发现设备";

    self.dataSource = [NSMutableArray array];
    
    CBCentralManager *centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    self.centralManager = centralManager;
    
}

#pragma mark - CBCentralManagerDelegate 代理方法
//中心服务器状态更新后
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    switch (central.state) {
        case CBPeripheralManagerStatePoweredOn:
            NSLog(@"BLE已打开.");
            [central scanForPeripheralsWithServices:nil options:nil];
            break;
            
        default:
            NSLog(@"此设备不支持BLE或未打开蓝牙功能，无法作为外围设备.");
            break;
    }
}

//发现设备
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *, id> *)advertisementData RSSI:(NSNumber *)RSSI{
    if (peripheral) {
        NSLog(@"发现设备 name = %@",peripheral.name);
        if (![self.dataSource containsObject:peripheral] && peripheral.name !=nil){
            [self.dataSource addObject:peripheral];
            [self.tableView reloadData];
        }
    }
    
}

-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    [self.tableView reloadData];
    [central stopScan];
    if (self.succeedPeripheral==nil) {
        self.succeedPeripheral = peripheral;
        NSLog(@"连接外围设备成功 name = %@",peripheral.name);

        LGConnectSuccessVC *vc = [[LGConnectSuccessVC alloc] init];
        vc.succeedPeripheral = peripheral;
        [self.navigationController pushViewController:vc animated:YES];
//        peripheral.delegate = self;
//        //外围设备开始寻找服务
//        [peripheral discoverServices:nil];
    }
}

-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    NSLog(@"连接外围设备失败 name = %@  error:%@",peripheral.name,error.localizedDescription);
    self.succeedPeripheral = nil;
    if (self.navigationController.viewControllers.count>2) {
        [self.navigationController popViewControllerAnimated:YES];
        [self.tableView reloadData];
        [self.centralManager scanForPeripheralsWithServices:nil options:nil];
    }
    //失败重新连接
//    [self.centralManager connectPeripheral:peripheral options:nil];
}

-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(nonnull CBPeripheral *)peripheral error:(nullable NSError *)error{
    NSLog(@"连接失败");
    self.succeedPeripheral = nil;
}

//#pragma mark - CBPeripheralDelegate 代理方法
//- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(nullable NSError *)error{
//    NSLog(@"已发现可用服务...");
//    if(error){
//        NSLog(@"外围设备寻找服务过程中发生错误，错误信息：%@",error.localizedDescription);
//    }
//    CBUUID *serviceUUID=[CBUUID UUIDWithString:kServiceUUID];
//    //遍历查找到的服务
//    for (CBService *service in peripheral.services) {
//        NSLog(@"查看服务%@",service.UUID);
//        if([service.UUID isEqual:serviceUUID]){
//            //外围设备查找指定服务中的特征
//            [peripheral discoverCharacteristics:nil forService:service];
//        }
//    }
//}

//-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
//    NSLog(@"已发现可用特征...");
//    if (error) {
//        NSLog(@"外围设备寻找特征过程中发生错误，错误信息：%@",error.localizedDescription);
//    }
//    //遍历服务中的特征
//    CBUUID *serviceUUID=[CBUUID UUIDWithString:kServiceUUID];
//    CBUUID *characteristicUUID=[CBUUID UUIDWithString:kCharacteristicUUID];
//    CBUUID *characteristicUUIDTWO=[CBUUID UUIDWithString:kCharacteristicUUIDTWO];
//    if([service.UUID isEqual:serviceUUID]){
//        for (CBCharacteristic *characteristic in service.characteristics) {
//            if ([characteristic.UUID isEqual:characteristicUUID]) {
////                NSLog(@"特征值为：%@",[[NSString alloc]initWithData:characteristic.value encoding:NSUTF8StringEncoding]);
////                if (characteristic.properties ==CBCharacteristicPropertyRead) {
////
//                    [peripheral readValueForCharacteristic:characteristic];
////                }
//                NSLog(@"订阅特征");
////                [peripheral setNotifyValue:YES forCharacteristic:characteristic];
//            }
////            else if ([characteristic.UUID isEqual:characteristicUUIDTWO]) {
////                if(characteristic.properties == CBCharacteristicPropertyNotify){
////                    [peripheral setNotifyValue:YES forCharacteristic:characteristic];
////                }
////            }
//
//        }
//    }
//
//}
//
//
//
//#pragma mark - 蓝牙数据接收
//- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
//    NSLog(@"======接收特征值");
//
//    if (error) {
//        NSLog(@"更新特征值时发生错误，错误信息：%@",error.localizedDescription);
//        return;
//    }
////    CBUUID *characteristicUUID=[CBUUID UUIDWithString:kCharacteristicUUID];
////    CBUUID *characteristicUUIDTWO=[CBUUID UUIDWithString:kCharacteristicUUIDTWO];
//
////    if (characteristic.properties ==CBCharacteristicPropertyRead) {
//        if (characteristic.value) {
//
////            NSString *orStr = characteristic.value.description;
////            NSString *str = [orStr substringWithRange:NSMakeRange(1, orStr.length - 2)];
////            NSString *dataStr = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
////            NSLog(@"特征值为dataStr = %@",dataStr);
//            NSLog(@"======读取特征值为：%@",[[NSString alloc]initWithData:characteristic.value encoding:NSUTF8StringEncoding]);
////        }else if(characteristic.properties == CBCharacteristicPropertyNotify){
////            NSLog(@"======更新特征值为：%@",[[NSString alloc]initWithData:characteristic.value encoding:NSUTF8StringEncoding]);
////        }
//    }
////        else if(characteristic.properties == CBCharacteristicPropertyNotify){
////        if ([characteristic.UUID isEqual:characteristicUUIDTWO]) {
////            if (characteristic.value) {
////            NSLog(@"======更新特征值为：%@",[[NSString alloc]initWithData:characteristic.value encoding:NSUTF8StringEncoding]);
////            }
////        }
////    }
//}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"cell"];
    }
    CBPeripheral *peripheral = self.dataSource[indexPath.row];
    cell.textLabel.text = peripheral.name;
    NSString *connectState = @"未连接";
    if(peripheral.state == CBPeripheralStateDisconnected){
        connectState = @"未连接";
    }else if(peripheral.state == CBPeripheralStateConnecting){
        connectState = @"正在连接";
    }else if(peripheral.state == CBPeripheralStateConnected){
        connectState = @"已连接";
    }else{
        connectState = @"正在断开连接";
    }
    cell.detailTextLabel.text = connectState;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CBPeripheral *peripheral = self.dataSource[indexPath.row];
    
    if (self.succeedPeripheral == peripheral) {
        LGConnectSuccessVC *vc = [[LGConnectSuccessVC alloc] init];
        vc.succeedPeripheral = self.succeedPeripheral;
        [self.navigationController pushViewController:vc animated:YES];
    }else {
        if (_succeedPeripheral) {
            [self.centralManager cancelPeripheralConnection:self.succeedPeripheral];
        }
        [self.centralManager connectPeripheral:peripheral options:nil];
        [self.tableView reloadData];
    }

}
@end
